import axios from '@/utils/http'
import { uploadUrl } from '@/utils/config'
import store from '@/store'
import sha1 from 'js-sha1'

/**
 * 对象去空格 
*/ 
export const removeEmptyVal = obj => {
    if(!obj) return;
    Object.keys(obj).forEach(k => {
        if(obj[k] === null || obj[k] === undefined || obj[k] === ''){
            delete obj[k]
        }
    })
    return obj
}

/**
 * 地址编码转码--- 地址用法也可采用ele的级联选择器
 * @param {*} code
 */
import VDistpicker from 'v-distpicker'
export const areaCode2Value = code => {
    code = code + '';
    return [/^\d\d/,/^\d\d\d\d/,/^\d\d\d\d\d\d/]
    .filter(reg => reg.test(code))
    .map(reg => "000000".replace(reg,code.match(reg)[0]))
    .map(code => VDistpicker.methods.getCodeValue(code*1))
}

/**
 * 获取token
 */
export const getAccessToken = function () {
    let tokenStr = sessionStorage.getItem('token')
    if(!tokenStr) return null
    return tokenStr
}

/**
 * 权限管理
 * 后台权限列表做出来
 */
export const authButton = function (id) {
    let menuList = store.state.menu.menuList
    let flag = false
    for(var i=0;i<menuList.length;i++){
        if(menuList[i].id == id){
            flag = true;
            break;
        }
    }
    return flag;
}

/**
 * 用户信息 -- 用于权限管理
 */
export const getUserInfo = (function(){
    let _memberInfo = ''
    return async function (){
        if(getAccessToken()){
            params.append('account',window.sessionStorage.getItem('account'))
            const { data } =await this.$axios.oauth.memberInfo(params)
            _memberInfo = data
        }
        return _memberInfo
    }
})

/**
 * 文件上传
 * @param {file} file 文件
 */
export const upload = function(file) {
    if (file && file.target) {
      file = file.target;
    }
    if (file && file.files) {
      file = file.files[0];
    }
    var reader = new FileReader();
    var p = new Promise(function(ok, error) {
      reader.addEventListener("load", function() {
        var code = sha1(reader.result).toUpperCase();
        fetch(`${uploadUrl}/exist?code=${code}`)
          .then(res => res.json())
          .then(json => {
            if (json.bizContent && json.bizContent.id) {
              return ok(json.bizContent);
            }
            var data = new FormData();
            data.append("file", file);
            return fetch(`${uploadUrl}/upload`, {
              method: "POST",
              body: data
            });
          })
          .then(res => res.json())
          .then(json => ok(json.bizContent))
          .catch(err => error(err));
      });
    });
    reader.readAsArrayBuffer(file);
    return p;
  };